package de.pharmacontrol.rfcserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
import java.util.logging.Logger;

import com.sap.conn.jco.ext.DestinationDataEventListener;
import com.sap.conn.jco.ext.DestinationDataProvider;

import de.pharmacontrol.jdni.JdniRepository;

public class PceDestinationDataProvider implements DestinationDataProvider{

	
	private final String fileName = "destination.xml";
	@Override
	public Properties getDestinationProperties(String destinationName) {
		Properties connectProperties = null;
		try {
			connectProperties = JdniRepository.getInstance().getDestinationProperties();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		
		if (connectProperties != null){
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info("DestinationProperties received from: " + JdniRepository.JCO_DESTINATION_CONTEXT);
			Logger.getLogger(Logger.GLOBAL_LOGGER_NAME).info(""+String.valueOf(connectProperties));
			return connectProperties;
		}
		File cfg = new File(fileName);
		if (cfg.exists()){
			try {
				connectProperties = new Properties();
				FileInputStream in = new FileInputStream(cfg);
				connectProperties.loadFromXML(in);
				in.close();
			} catch (Exception e) {
				System.err.println("Unable to read the destination file " + cfg.getName() + ": " + e.getMessage());
				connectProperties =  getDefaultProps();
			}
		}else{
			connectProperties = getDefaultProps();
			createFile(cfg, connectProperties);
		}
		return connectProperties;
	}

	private Properties getDefaultProps(){
		
		Properties connectProperties = new Properties();
		connectProperties.setProperty(DestinationDataProvider.JCO_ASHOST, "localhost");
		connectProperties.setProperty(DestinationDataProvider.JCO_SYSNR, "53");
		connectProperties.setProperty(DestinationDataProvider.JCO_CLIENT, "000");
		connectProperties.setProperty(DestinationDataProvider.JCO_USER, "user");
		connectProperties.setProperty(DestinationDataProvider.JCO_PASSWD, "pwd");
		connectProperties.setProperty(DestinationDataProvider.JCO_LANG, "DE");
		connectProperties.setProperty(DestinationDataProvider.JCO_POOL_CAPACITY, "3");
		connectProperties.setProperty(DestinationDataProvider.JCO_PEAK_LIMIT, "10");
		
		return connectProperties;
	}
	
	private void createFile(File cfg, Properties properties) {
		if (!cfg.exists()) {
			try {
				FileOutputStream fos = new FileOutputStream(cfg, false);
				properties.storeToXML(fos, "PCE Destination");
				fos.close();
			} catch (Exception e) {
				System.err.println("Unable to create the destination file " + cfg.getName()+": "+ e.getMessage());
			}
		}
	}
	
	@Override
	public void setDestinationDataEventListener(DestinationDataEventListener eventListener) {	
	}

	@Override
	public boolean supportsEvents() {
		return false;
	}

}
